package com.antd.admin.server.strategy.passwd;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.antd.admin.api.dto.ResetPasswdDto;
import com.antd.admin.api.entity.SysUser;
import com.antd.admin.server.service.ISysUserService;
import com.antd.common.auth.util.AntdSecurityUtil;
import com.antd.common.core.constant.AntdConstant;
import com.antd.common.core.exception.BaseException;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

/**
 * TODO
 *
 * @author 子丶沫
 * @version 1.0
 * @date 2020/12/5 16:18
 */
@Slf4j
@Component("resetPasswd"+AntdConstant.RESET_EMAIL)
public class ResetPasswdEmailHandler implements ResetPasswdHandler{
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private ISysUserService userService;
    @Override
    public boolean resetPassword(ResetPasswdDto resetPasswdDto) {
        String email = resetPasswdDto.getEmail();
        if(StrUtil.isBlank(email)){
            throw new BaseException("邮箱地址不能为空.");
        }
        String emailCode = resetPasswdDto.getEmailCode();
        if(StrUtil.isBlank(emailCode)){
            throw new BaseException("邮箱验证码不能为空.");
        }
        String code = redisTemplate.opsForValue().get(AntdConstant.ANTD_EMAIL_CODE_KEY + email);
        if(StrUtil.isBlank(code)){
            throw new BaseException("验证码已过期");
        }
        if(!emailCode.equalsIgnoreCase(code)){
            throw new BaseException("验证码错误.");
        }
        redisTemplate.delete(AntdConstant.ANTD_EMAIL_CODE_KEY + email);
        SysUser sysUser = userService.getOne(Wrappers.<SysUser>query().lambda().eq(SysUser::getEmail, email));
        if(ObjectUtil.isNull(sysUser)){
            throw new BaseException("未找到与此邮箱地址相关的用户，请检查您的信息");
        }
        sysUser.setPassword(AntdSecurityUtil.encodePassword(resetPasswdDto.getPassword()));
        return userService.updateById(sysUser);
    }
}
